package com.sky.service.impl;

import com.sky.annotation.ComputeTime;
import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.OrderReport;
import com.sky.entity.Orders;
import com.sky.entity.TurnoverReport;
import com.sky.entity.UserReport;
import com.sky.mapper.OrdersMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkSpaceService;
import com.sky.vo.*;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class ReportServiceImpl implements ReportService {
    @Autowired
    private OrdersMapper ordersMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WorkSpaceService workSpaceService;

    /**
     * 营业额统计
     *
     * @param begin
     * @param end
     * @return
     */
    @ComputeTime
    @Override
    public TurnoverReportVO turnoverStatistics(LocalDate begin, LocalDate end) {
        // 根据begin和end获取日期列表
        List<LocalDate> dates = generateDates(begin, end);
        // 查询每一天的营业额列表 select sum(amount) from orders where status = #{status} and  date(order_time) = '2024-06-02'; TODO 此处可以通过group by语句解决循环查找数据库的问题
//        List<Integer> turnovers = new ArrayList<>();
//        dates.forEach(date -> {
//            Integer turnover = ordersMapper.getSumAmountByStatusAndOrderTime(Orders.COMPLETED, date);
//            if (turnover == null){
//                turnovers.add(0);
//            }else {
//                turnovers.add(turnover);
//            }
//        });
        // 按照下单日期分组查询已完成订单的营业额
        List<TurnoverReport> turnoversReportDB = ordersMapper.getSumAmountGroupByOrderTime(Orders.COMPLETED, begin ,end);

        // 使用Stream API获取每个日期的营业额
        List<Double> turnovers = dates.stream()
                .map(date -> turnoversReportDB.stream()
                        .filter(turnoverReport -> turnoverReport.getDate().equals(date))
                        .findFirst()
                        .map(TurnoverReport::getSumAmount)
                        .orElse(0.0)) // 如果没有找到对应日期的订单记录，则返回0.0
                .collect(Collectors.toList());

        // list转逗号分隔的字符串
        String dateList = StringUtils.join(dates, ",");
        String turnoverList = StringUtils.join(turnovers, ",");

        // 封装VO返回结果
        return TurnoverReportVO.builder()
                .dateList(dateList)
                .turnoverList(turnoverList).build();
    }

    /**
     * 用户统计
     *
     * @param begin
     * @param end
     * @return
     */
    @ComputeTime
    @Override
    public UserReportVO userStatistics(LocalDate begin, LocalDate end) {
        // 根据begin和end获取日期列表
        List<LocalDate> dates = generateDates(begin, end);

        // 按照创建日期分组查询新增用户数
        List<UserReport> newUserReportsDB = userMapper.countNewUserGroupByCreateTime(begin, end);

        // 按照创建日期查询总用户数
        List<Integer> totalUsers = new ArrayList<>();
        dates.forEach(date -> {
            Integer totalUser = userMapper.countTotalUserByCreateTime(date);
            if (totalUser == null){
                totalUsers.add(0);
            }else {
                totalUsers.add(totalUser);
            }
        });

        // 使用Stream API获取每个日期的新增用户数和总用户数
        List<Integer> newUsers = dates.stream()
                .map(date -> newUserReportsDB.stream()
                        .filter(newUserReport -> newUserReport.getDate().equals(date))
                        .findFirst()
                        .map(UserReport::getCountUser)
                        .orElse(0)) // 如果没有找到对应日期的新增用户数，则返回0
                .collect(Collectors.toList());

        // list转逗号分隔的字符串
        String dateList = StringUtils.join(dates, ",");
        String newUserList = StringUtils.join(newUsers, ",");
        String totalUserList = StringUtils.join(totalUsers, ",");

        // 封装VO返回结果
        return UserReportVO.builder()
                .dateList(dateList)
                .newUserList(newUserList)
                .totalUserList(totalUserList)
                .build();

    }

    /**
     * 订单统计
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public OrderReportVO ordersStatistics(LocalDate begin, LocalDate end) {
        // 根据begin和end获取日期列表
        List<LocalDate> dates = generateDates(begin, end);

        // 按照创建日期分组查询有效订单数
        Map map = new HashMap();
        map.put("begin", begin);
        map.put("end", end);
        map.put("status", Orders.COMPLETED);
        List<OrderReport> validOrderReportsDB = ordersMapper.countOrderByMap(map);

        // 按照创建日期分组查询总订单数
        map.put("status", null);
        List<OrderReport> totalOrderReportsDB = ordersMapper.countOrderByMap(map);

        // 使用Stream API获取每个日期的有效订单数和总订单数
        List<Integer> validOrderCounts = dates.stream()
                .map(date -> validOrderReportsDB.stream()
                        .filter(validOrderReport -> validOrderReport.getDate().equals(date))
                        .findFirst()
                        .map(OrderReport::getCountOrder)
                        .orElse(0)) // 如果没有找到对应日期的有效订单数，则返回0
                .collect(Collectors.toList());

        List<Integer> totalOrderCounts = dates.stream()
                .map(date -> totalOrderReportsDB.stream()
                        .filter(totalOrderReport -> totalOrderReport.getDate().equals(date))
                        .findFirst()
                        .map(OrderReport::getCountOrder)
                        .orElse(0)) // 如果没有找到对应日期的有效订单数，则返回0
                .collect(Collectors.toList());

        // 计算有效订单数和订单总数以及订单完成率
        Integer validOrderCount = validOrderCounts.stream().mapToInt(Integer::intValue).sum();
        Integer totalOrderCount = totalOrderCounts.stream().mapToInt(Integer::intValue).sum();
        Double orderCompletionRate = validOrderCount / (double) totalOrderCount;

        // list转逗号分隔的字符串
        String dateList = StringUtils.join(dates, ",");
        String validOrderCountList = StringUtils.join(validOrderCounts, ",");
        String orderCountList = StringUtils.join(totalOrderCounts, ",");

        // 封装VO返回结果
        return OrderReportVO.builder()
                .dateList(dateList)
                .validOrderCountList(validOrderCountList)
                .orderCountList(orderCountList)
                .validOrderCount(validOrderCount)
                .totalOrderCount(totalOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();
    }

    /**
     * 查询销量排名top10接口
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public SalesTop10ReportVO getSalesTop10(LocalDate begin, LocalDate end) {
        List<GoodsSalesDTO> salesTop10 = ordersMapper.getSalesTop10(begin, end);

        List<String> names = salesTop10.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        List<Integer> numbers = salesTop10.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());
        String nameList = StringUtils.join(names, ",");
        String numberList = StringUtils.join(numbers, ",");

        return SalesTop10ReportVO
                .builder()
                .nameList(nameList)
                .numberList(numberList)
                .build();
    }

    private List<LocalDate> generateDates(LocalDate begin, LocalDate end){
        // 根据begin和end获取日期列表
        List<LocalDate> dates = new ArrayList<>();
        dates.add(begin);
        while (!begin.equals(end)){
            begin = begin.plusDays(1);
            dates.add(begin);
        }
        return dates;
    }
    /**
     * 导出近三十日订单数据到浏览器
     */
    @Override
    public void exportBusinessData(HttpServletResponse response) {

        try (
                InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
                XSSFWorkbook excel = new XSSFWorkbook(in)

        ) {
            // 生成日期写入excel
            LocalDate beginDate = LocalDate.now().minusDays(30);
            LocalDate endDate = LocalDate.now().minusDays(1);

            XSSFSheet sheet = excel.getSheet("Sheet1");
            sheet.getRow(1).getCell(1).setCellValue("统计日期：" + beginDate + "-" + endDate);

            // 查询概览数据，写入excel
            BusinessDataVO businessDataVO = workSpaceService.businessData(beginDate, endDate);

            sheet.getRow(3).getCell(2).setCellValue(businessDataVO.getTurnover());
            sheet.getRow(3).getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
            sheet.getRow(3).getCell(6).setCellValue(businessDataVO.getNewUsers());
            sheet.getRow(4).getCell(2).setCellValue(businessDataVO.getValidOrderCount());
            sheet.getRow(4).getCell(4).setCellValue(businessDataVO.getUnitPrice());

            // 查询明细数据，写入excel
            for (int i = 0; i < 30; i++) {
                LocalDate date = beginDate.plusDays(i);
                BusinessDataVO businessData = workSpaceService.businessData(date, date);

                sheet.getRow(7 + i).getCell(1).setCellValue(date.toString());
                sheet.getRow(7 + i).getCell(2).setCellValue(businessData.getTurnover());
                sheet.getRow(7 + i).getCell(3).setCellValue(businessData.getValidOrderCount());
                sheet.getRow(7 + i).getCell(4).setCellValue(businessData.getOrderCompletionRate());
                sheet.getRow(7 + i).getCell(5).setCellValue(businessData.getUnitPrice());
                sheet.getRow(7 + i).getCell(6).setCellValue(businessData.getNewUsers());
            }

            // 将excel写入浏览器的输出流
            ServletOutputStream outputStream = response.getOutputStream();
            excel.write(outputStream);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
